package com.justgame.project.cloud.common.config;

import com.justgame.project.cloud.common.constant.Const;
import com.justgame.project.cloud.common.enums.TimeEnum;
import com.justgame.project.cloud.common.util.RedisUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.web.client.RestTemplate;

import java.util.UUID;

@Configuration
@AllArgsConstructor
public class FeignConfig implements RequestInterceptor {
    private final RedisUtils redisUtils;
    private final Environment environment;

    @Override
    public void apply(RequestTemplate template) {
        /* 生成一个用于服务提供者端验证是否是Feign发送来请求的唯一标识 */
        String uuid = UUID.randomUUID().toString();
        String applicationName = environment.getProperty("spring.application.name");
        /* 将这个标识存储与Redis当中 */
        redisUtils.set(String.format("%s%s",Const.FEIGN_REQUEST_REDIS_AUTH,uuid),applicationName, TimeEnum.MINUTE.getTime(3) / 1000);
        /* 携带到请求头上 */
        template.header(Const.FEIGN_REQUEST_HEADER_AUTH, uuid);
        template.header(Const.FEIGN_REQUEST_HEADER_APP_NAME,applicationName);
    }

    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

}
